package com.mall.user.services;

import com.alibaba.druid.support.json.JSONUtils;
import com.mall.user.ILoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.CheckAuthRequest;
import com.mall.user.dto.CheckAuthResponse;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import com.mall.user.utils.JwtTokenUtils;
import com.mall.user.utils.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:tanxin Desc:
 * @date:2020/7/10 9:00
 */
@Slf4j
@Component
@Service
public class UserLoginServiceImpl implements ILoginService {

    @Resource
    MemberMapper memberMapper;
    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        UserLoginResponse loginResponse = new UserLoginResponse();
        log.info("请求体："+request);
        //判空
        try {
            //request.requestCheck();
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("state",1).andEqualTo("username",request.getUserName());
            List<Member> members = memberMapper.selectByExample(example);
            if (members == null || members.size() == 0) {
                loginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
                loginResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
                return loginResponse;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //验证用户是否激活
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUserName());
        Member member = memberMapper.selectOneByExample(example);
        // n 表示未激活的用户
        if ("N".equals(member.getIsVerified()) || "n".equals(member.getIsVerified())){
            loginResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            loginResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
        }else{
            //用户名和id放进Map中，生成token
            HashMap<String, Object> map = new HashMap<>(16);
            map.put("uid",member.getId());
            map.put("userName",member.getUsername());
            map.put("password",request.getPassword());
            String token = JwtTokenUtils.builder().msg(JSONUtils.toJSONString(map)).build().creatJwtToken();
            loginResponse.setToken(token);
            loginResponse.setId(member.getId());
            loginResponse.setState(1);
            loginResponse.setUsername(request.getUserName());
            loginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            loginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }
        //生成token返回
        return loginResponse;
    }

    @Override
    public CheckAuthResponse validToken(CheckAuthRequest request) {

        CheckAuthResponse response = new CheckAuthResponse();
        //获取token
        String token = request.getToken();
        //校验token
        try {
            request.setToken(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //解密token
        String info = JwtTokenUtils.builder().token(token).build().freeJwt();
        Map map = (Map) JSONUtils.parse(info);
        //前端传来的用户
        String userName = (String) map.get("userName");
        //要验证的明文密码
        String plaintext = (String) map.get("password");
        //加密密码
//        String md5Pwd = null;
//        try {
//            md5Pwd = Md5Util.getMd5(password);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
      //  String bCryptPwd = BCrypt.hashpw(plaintext, BCrypt.gensalt());
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",userName);

        Member member = memberMapper.selectOneByExample(example);
        if (member == null){
            response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
        }
        //数据库中取出的密文
        String password = member.getPassword();
        boolean checkpw = BCrypt.checkpw(plaintext, password);
        if (member != null && checkpw){
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            response.setUserinfo(info);
        }
        else{
            response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
        }
        return response;
    }
}
